package agricultural.system;

import java.util.*;
import java.time.LocalDateTime;

class Field {
    private String id;
    private String name;
    private double area; // 平方米
    private String crop;
    private EnvironmentData lastEnvironmentData;

    public Field(String id, String name, double area, String crop) {
        this.id = id;
        this.name = name;
        this.area = area;
        this.crop = crop;
    }

    // Getters
    public String getId() { return id; }
    public String getName() { return name; }
    public double getArea() { return area; }
    public String getCrop() { return crop; }
    public EnvironmentData getLastEnvironmentData() { return lastEnvironmentData; }

    // Setter
    public void setLastEnvironmentData(EnvironmentData data) {
        this.lastEnvironmentData = data;
    }
}

class Task {
    public enum Status {
        CREATED, RUNNING, COMPLETED, FAILED
    }

    private String id;
    private String name;
    private Field field;
    private AgriculturalMachine machine;
    private String description;
    private Status status = Status.CREATED;
    private LocalDateTime createTime;
    private LocalDateTime startTime;
    private LocalDateTime endTime;

    public Task(String id, String name, Field field, AgriculturalMachine machine, String description) {
        this.id = id;
        this.name = name;
        this.field = field;
        this.machine = machine;
        this.description = description;
        this.createTime = LocalDateTime.now();
    }

    // Getters
    public String getId() { return id; }
    public String getName() { return name; }
    public Field getField() { return field; }
    public AgriculturalMachine getMachine() { return machine; }
    public String getDescription() { return description; }
    public Status getStatus() { return status; }
    public LocalDateTime getCreateTime() { return createTime; }
    public LocalDateTime getStartTime() { return startTime; }
    public LocalDateTime getEndTime() { return endTime; }

    // Methods
    public void start() {
        this.status = Status.RUNNING;
        this.startTime = LocalDateTime.now();
        System.out.println("任务 [" + name + "] 开始执行");
    }

    public void stop() {
        this.status = Status.COMPLETED;
        this.endTime = LocalDateTime.now();
        System.out.println("任务 [" + name + "] 已完成");
    }
}

class User {
    public enum Role {
        ADMIN, OPERATOR, VIEWER
    }

    private String username;
    private String realName;
    private String password;
    private Role role;

    public User(String username, String realName, String password, Role role) {
        this.username = username;
        this.realName = realName;
        this.password = password;
        this.role = role;
    }

    // Getters
    public String getUsername() { return username; }
    public String getRealName() { return realName; }
    public String getPassword() { return password; }
    public Role getRole() { return role; }
}

class Logger {
    private static Logger instance = new Logger();
    private List<String> logs = new ArrayList<>();

    private Logger() {} // 私有构造函数

    public static Logger getInstance() {
        return instance;
    }

    public void log(String message) {
        String logEntry = LocalDateTime.now() + " - " + message;
        logs.add(logEntry);
        System.out.println(logEntry);
    }

    public void showLog() {
        System.out.println("\n=== 系统日志 ===");
        for (String log : logs) {
            System.out.println(log);
        }
    }
}

class Sprayer implements AgriculturalMachine {
    private String type = "喷药机";
    private MachineState state;
    private PathPlanningStrategy pathStrategy;
    private String location = "原点";
    private double fuelLevel = 95.0;
    private Task currentTask;
    private double pesticideLevel = 100.0;

    public Sprayer() {
        this.state = new IdleState();
        this.pathStrategy = new NormalPathStrategy();
    }

    @Override
    public void start(Task task) {
        this.currentTask = task;
        this.state = new WorkingState();
        state.execute(this);
        System.out.println("开始任务: " + task.getName() + " 在 " + task.getField().getName());
        System.out.println("农药剩余: " + pesticideLevel + "%");
        simulateFuelConsumption();
    }

    @Override
    public void stop() {
        this.state = new MaintenanceState();
        state.execute(this);
        if (currentTask != null) {
            System.out.println("停止任务: " + currentTask.getName());
            currentTask = null;
        }
    }

    @Override
    public void changePath(Field field) {
        System.out.println(pathStrategy.planPath(field, this));
        updateLocation(field);
    }

    @Override
    public void update(EnvironmentData data) {
        System.out.println(type + " 收到 " + data.getField().getName() + " 的环境数据更新");

        if (currentTask != null && !currentTask.getField().getId().equals(data.getField().getId())) {
            System.out.println("当前任务在其他农田，忽略此环境数据");
            return;
        }

        if (data.isHasObstacle()) {
            this.state = new AlertState();
            state.execute(this);
            changePath(data.getField());
        } else if (data.getWindSpeed() > 5) {
            System.out.println(type + " 调整喷洒策略：风速过高，减少喷洒量");
        } else {
            this.state = new WorkingState();
            state.execute(this);
            changePath(data.getField());
        }
    }

    @Override
    public void setState(MachineState state) {
        this.state = state;
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        this.pathStrategy = strategy;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getStatus() {
        return type + " 当前状态: " + state.getStateName() + ", 农药剩余: " + pesticideLevel + "%";
    }

    @Override
    public String getLocation() {
        return location;
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        System.out.println("调整 " + type + " 的 " + parameter + " 至 " + value);
        if ("sprayRate".equalsIgnoreCase(parameter)) {
            System.out.println("设置喷洒速率: " + value + " 升/亩");
        } else if ("pressure".equalsIgnoreCase(parameter)) {
            System.out.println("设置喷洒压力: " + value + " MPa");
        } else {
            System.out.println("未知参数: " + parameter);
        }
    }

    private void updateLocation(Field field) {
        this.location = field.getName() + "区域内";
        System.out.println(type + " 位置更新为: " + location);
    }

    private void simulateFuelConsumption() {
        this.fuelLevel -= Math.random() * 2;
        this.pesticideLevel -= Math.random() * 8;

        if (fuelLevel < 20) {
            SafetyRequest request = new SafetyRequest(
                    SafetyRequest.Type.LOW_FUEL,
                    type + " 燃油不足",
                    fuelLevel,
                    2.5
            );
            SafetyHandler safetyChain = new LowFuelHandler();
            safetyChain.handleRequest(request);
        }

        if (pesticideLevel < 10) {
            System.out.println("警告: 农药即将耗尽，剩余 " + pesticideLevel + "%");
        }
    }
}

// 1. 工厂方法模式：创建不同类型的农机设备
interface AgriculturalMachineFactory {
    AgriculturalMachine createMachine();
}

class TractorFactory implements AgriculturalMachineFactory {
    @Override
    public AgriculturalMachine createMachine() {
        return new Tractor();
    }
}

class SeederFactory implements AgriculturalMachineFactory {
    @Override
    public AgriculturalMachine createMachine() {
        return new Seeder();
    }
}

class HarvesterFactory implements AgriculturalMachineFactory {
    @Override
    public AgriculturalMachine createMachine() {
        return new Harvester();
    }
}

class SprayerFactory implements AgriculturalMachineFactory {
    @Override
    public AgriculturalMachine createMachine() {
        return new Sprayer();
    }
}

// 2. 策略模式：实现不同环境下的路径规划算法
interface PathPlanningStrategy {
    String planPath(Field field, AgriculturalMachine machine);
}

class NormalPathStrategy implements PathPlanningStrategy {
    @Override
    public String planPath(Field field, AgriculturalMachine machine) {
        return machine.getType() + " 正常路径规划: 覆盖整个" + field.getName();
    }
}

class WetSoilPathStrategy implements PathPlanningStrategy {
    @Override
    public String planPath(Field field, AgriculturalMachine machine) {
        return machine.getType() + " 湿土路径规划: 避开" + field.getName() + "湿度>70%的区域";
    }
}

class ObstacleAvoidancePathStrategy implements PathPlanningStrategy {
    @Override
    public String planPath(Field field, AgriculturalMachine machine) {
        return machine.getType() + " 避障路径规划: 在" + field.getName() + "中检测到障碍物，启动绕行";
    }
}

class CollaborativePathStrategy implements PathPlanningStrategy {
    @Override
    public String planPath(Field field, AgriculturalMachine machine) {
        return machine.getType() + " 协同路径规划: 与其他设备配合作业，优化" + field.getName() + "资源分配";
    }
}

// 3. 观察者模式：处理传感器数据采集和状态监控
interface Observer {
    void update(EnvironmentData data);
}

interface Subject {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

class EnvironmentData {
    private Field field;
    private double soilMoisture;
    private double soilPH;
    private double nutrientLevel;
    private double temperature;
    private double humidity;
    private double windSpeed;
    private boolean hasObstacle;

    public EnvironmentData(Field field, double soilMoisture, double soilPH, double nutrientLevel,
                           double temperature, double humidity, double windSpeed, boolean hasObstacle) {
        this.field = field;
        this.soilMoisture = soilMoisture;
        this.soilPH = soilPH;
        this.nutrientLevel = nutrientLevel;
        this.temperature = temperature;
        this.humidity = humidity;
        this.windSpeed = windSpeed;
        this.hasObstacle = hasObstacle;
    }

    // Getters
    public Field getField() { return field; }
    public double getSoilMoisture() { return soilMoisture; }
    public double getSoilPH() { return soilPH; }
    public double getNutrientLevel() { return nutrientLevel; }
    public double getTemperature() { return temperature; }
    public double getHumidity() { return humidity; }
    public double getWindSpeed() { return windSpeed; }
    public boolean isHasObstacle() { return hasObstacle; }

    @Override
    public String toString() {
        return "环境数据 - " + field.getName() + ": " +
                "土壤湿度=" + soilMoisture +
                ", 土壤pH=" + soilPH +
                ", 养分含量=" + nutrientLevel +
                ", 温度=" + temperature + "°C" +
                ", 湿度=" + humidity + "%" +
                ", 风速=" + windSpeed + "m/s" +
                ", 障碍物=" + (hasObstacle ? "有" : "无");
    }
}

class SensorSystem implements Subject {
    private List<Observer> observers;
    private EnvironmentData data;

    public SensorSystem() {
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(data);
        }
    }

    public void setEnvironmentData(EnvironmentData data) {
        this.data = data;
        notifyObservers();
    }
}

// 4. 状态模式：管理农机的各种工作状态转换
interface MachineState {
    void execute(AgriculturalMachine machine);
    String getStateName();
}

class WorkingState implements MachineState {
    @Override
    public void execute(AgriculturalMachine machine) {
        System.out.println(machine.getType() + " 正在作业");
        machine.setPathPlanningStrategy(new NormalPathStrategy());
    }

    @Override
    public String getStateName() {
        return "工作中";
    }
}

class AlertState implements MachineState {
    @Override
    public void execute(AgriculturalMachine machine) {
        System.out.println(machine.getType() + " 收到警报，准备调整");
        machine.setPathPlanningStrategy(new ObstacleAvoidancePathStrategy());
    }

    @Override
    public String getStateName() {
        return "警报";
    }
}

class MaintenanceState implements MachineState {
    @Override
    public void execute(AgriculturalMachine machine) {
        System.out.println(machine.getType() + " 正在维护，停止作业");
    }

    @Override
    public String getStateName() {
        return "维护中";
    }
}

class IdleState implements MachineState {
    @Override
    public void execute(AgriculturalMachine machine) {
        System.out.println(machine.getType() + " 处于空闲状态，等待任务");
    }

    @Override
    public String getStateName() {
        return "空闲";
    }
}

// 5. 责任链模式：处理系统异常和紧急事件
abstract class SafetyHandler {
    protected SafetyHandler nextHandler;

    public void setNextHandler(SafetyHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handleRequest(SafetyRequest request);
}

class ObstacleHandler extends SafetyHandler {
    @Override
    public void handleRequest(SafetyRequest request) {
        if (request.getType() == SafetyRequest.Type.OBSTACLE) {
            System.out.println("紧急避障策略: " + request.getDescription());
            System.out.println("1. 启动传感器精确定位");
            System.out.println("2. 计算绕行路径");
            System.out.println("3. 通知其他设备调整路径");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

class WetSoilHandler extends SafetyHandler {
    @Override
    public void handleRequest(SafetyRequest request) {
        if (request.getType() == SafetyRequest.Type.WET_SOIL) {
            System.out.println("湿土处理策略: " + request.getDescription());
            System.out.println("1. 调整播种深度");
            System.out.println("2. 降低行驶速度");
            System.out.println("3. 增加土壤透气性检测");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

class FaultHandler extends SafetyHandler {
    @Override
    public void handleRequest(SafetyRequest request) {
        if (request.getType() == SafetyRequest.Type.FAULT) {
            System.out.println("故障处理策略: " + request.getDescription());
            System.out.println("1. 记录故障代码: " + request.getDetailCode());
            System.out.println("2. 执行紧急停止程序");
            System.out.println("3. 发送故障报告至维修中心");
            System.out.println("4. 启动备用设备");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

class LowFuelHandler extends SafetyHandler {
    @Override
    public void handleRequest(SafetyRequest request) {
        if (request.getType() == SafetyRequest.Type.LOW_FUEL) {
            System.out.println("低油量策略: " + request.getDescription());
            System.out.println("1. 当前油量: " + request.getFuelLevel() + "%");
            System.out.println("2. 最近加油站距离: " + request.getDistanceToFuelStation() + "km");
            System.out.println("3. 规划返回加油站路径");
            System.out.println("4. 通知调度中心安排加油");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

class SafetyRequest {
    public enum Type {
        OBSTACLE, WET_SOIL, FAULT, LOW_FUEL
    }

    private Type type;
    private String description;
    private int detailCode; // 故障代码
    private double fuelLevel; // 油量百分比
    private double distanceToFuelStation; // 到加油站距离

    public SafetyRequest(Type type, String description) {
        this.type = type;
        this.description = description;
    }

    public SafetyRequest(Type type, String description, int detailCode) {
        this(type, description);
        this.detailCode = detailCode;
    }

    public SafetyRequest(Type type, String description, double fuelLevel, double distanceToFuelStation) {
        this(type, description);
        this.fuelLevel = fuelLevel;
        this.distanceToFuelStation = distanceToFuelStation;
    }

    public Type getType() {
        return type;
    }

    public String getDescription() {
        return description;
    }

    public int getDetailCode() {
        return detailCode;
    }

    public double getFuelLevel() {
        return fuelLevel;
    }

    public double getDistanceToFuelStation() {
        return distanceToFuelStation;
    }
}

// 6. 命令模式：封装农机操作指令
interface Command {
    void execute();
    String getDescription();
}

class StartCommand implements Command {
    private AgriculturalMachine machine;
    private Task task;

    public StartCommand(AgriculturalMachine machine, Task task) {
        this.machine = machine;
        this.task = task;
    }

    @Override
    public void execute() {
        System.out.println("执行命令: 启动 " + machine.getType() + " 执行任务 [" + task.getName() + "]");
        machine.start(task);
    }

    @Override
    public String getDescription() {
        return "启动 " + machine.getType() + " 执行任务 [" + task.getName() + "]";
    }
}

class StopCommand implements Command {
    private AgriculturalMachine machine;

    public StopCommand(AgriculturalMachine machine) {
        this.machine = machine;
    }

    @Override
    public void execute() {
        System.out.println("执行命令: 停止 " + machine.getType());
        machine.stop();
    }

    @Override
    public String getDescription() {
        return "停止 " + machine.getType();
    }
}

class ChangePathCommand implements Command {
    private AgriculturalMachine machine;
    private Field field;
    private PathPlanningStrategy strategy;

    public ChangePathCommand(AgriculturalMachine machine, Field field, PathPlanningStrategy strategy) {
        this.machine = machine;
        this.field = field;
        this.strategy = strategy;
    }

    @Override
    public void execute() {
        System.out.println("执行命令: 更改 " + machine.getType() + " 在 " + field.getName() + " 的路径策略");
        machine.setPathPlanningStrategy(strategy);
        machine.changePath(field);
    }

    @Override
    public String getDescription() {
        return "更改 " + machine.getType() + " 在 " + field.getName() + " 的路径策略";
    }
}

class AdjustParameterCommand implements Command {
    private AgriculturalMachine machine;
    private String parameter;
    private double value;

    public AdjustParameterCommand(AgriculturalMachine machine, String parameter, double value) {
        this.machine = machine;
        this.parameter = parameter;
        this.value = value;
    }

    @Override
    public void execute() {
        System.out.println("执行命令: 调整 " + machine.getType() + " 的 " + parameter + " 至 " + value);
        machine.adjustParameter(parameter, value);
    }

    @Override
    public String getDescription() {
        return "调整 " + machine.getType() + " 的 " + parameter + " 至 " + value;
    }
}

class CommandInvoker {
    private List<Command> history = new ArrayList<>();

    public void executeCommand(Command command) {
        command.execute();
        history.add(command);
        Logger.getInstance().log("执行命令: " + command.getDescription());
    }

    public void showHistory() {
        System.out.println("\n=== 命令执行历史 ===");
        for (int i = 0; i < history.size(); i++) {
            System.out.println((i + 1) + ". " + history.get(i).getDescription());
        }
    }
}

// 7. 外观模式：提供简化的系统接口
class AgriculturalSystemFacade {
    private Map<String, AgriculturalMachine> machines = new HashMap<>();
    private Map<String, Field> fields = new HashMap<>();
    private Map<String, Task> tasks = new HashMap<>();
    private List<User> users = new ArrayList<>();
    private SensorSystem sensorSystem;
    private CommandInvoker invoker;
    private SafetyHandler safetyChain;
    private Logger logger;

    public AgriculturalSystemFacade() {
        sensorSystem = new SensorSystem();
        invoker = new CommandInvoker();
        logger = Logger.getInstance();

        // 构建责任链
        SafetyHandler obstacleHandler = new ObstacleHandler();
        SafetyHandler wetSoilHandler = new WetSoilHandler();
        SafetyHandler faultHandler = new FaultHandler();
        SafetyHandler lowFuelHandler = new LowFuelHandler();

        obstacleHandler.setNextHandler(wetSoilHandler);
        wetSoilHandler.setNextHandler(faultHandler);
        faultHandler.setNextHandler(lowFuelHandler);
        safetyChain = obstacleHandler;

        // 初始化一些默认数据
        initializeDefaultData();
    }

    private void initializeDefaultData() {
        // 添加默认用户
        users.add(new User("admin", "管理员", "admin123", User.Role.ADMIN));
        users.add(new User("operator", "操作员", "operator123", User.Role.OPERATOR));
        users.add(new User("viewer", "查看者", "viewer123", User.Role.VIEWER));

        // 添加默认农田
        fields.put("field1", new Field("field1", "北田", 10000, "小麦"));
        fields.put("field2", new Field("field2", "南田", 8000, "玉米"));

        // 添加默认农机
        addMachine("tractor1", new TractorFactory().createMachine());
        addMachine("seeder1", new SeederFactory().createMachine());
        addMachine("harvester1", new HarvesterFactory().createMachine());

        // 注册观察者
        for (AgriculturalMachine machine : machines.values()) {
            sensorSystem.registerObserver(machine);
        }
    }

    // 农机设备管理
    public void addMachine(String id, AgriculturalMachine machine) {
        machines.put(id, machine);
        sensorSystem.registerObserver(machine);
        logger.log("添加农机: " + id + " (" + machine.getType() + ")");
    }

    public void removeMachine(String id) {
        AgriculturalMachine machine = machines.remove(id);
        if (machine != null) {
            sensorSystem.removeObserver(machine);
            logger.log("移除农机: " + id + " (" + machine.getType() + ")");
        }
    }

    public void showAllMachines() {
        System.out.println("\n=== 农机设备列表 ===");
        for (Map.Entry<String, AgriculturalMachine> entry : machines.entrySet()) {
            String id = entry.getKey();
            AgriculturalMachine machine = entry.getValue();
            System.out.println("ID: " + id + ", 类型: " + machine.getType() + ", 状态: " + machine.getStatus());
            System.out.println("位置: " + machine.getLocation() + ", 油量: " + machine.getFuelLevel() + "%");
        }
    }

    public AgriculturalMachine getMachine(String id) {
        return machines.get(id);
    }

    // 农田环境监测
    public void addField(String id, Field field) {
        fields.put(id, field);
        logger.log("添加农田: " + id + " (" + field.getName() + ")");
    }

    public void showAllFields() {
        System.out.println("\n=== 农田列表 ===");
        for (Map.Entry<String, Field> entry : fields.entrySet()) {
            String id = entry.getKey();
            Field field = entry.getValue();
            System.out.println("ID: " + id + ", 名称: " + field.getName() +
                    ", 面积: " + field.getArea() + "平方米, 作物: " + field.getCrop());
        }
    }

    public void updateEnvironment(String fieldId, double soilMoisture, double soilPH, double nutrientLevel,
                                  double temperature, double humidity, double windSpeed, boolean hasObstacle) {
        Field field = fields.get(fieldId);
        if (field != null) {
            System.out.println("\n=== 更新 " + field.getName() + " 的环境数据 ===");
            EnvironmentData data = new EnvironmentData(field, soilMoisture, soilPH, nutrientLevel,
                    temperature, humidity, windSpeed, hasObstacle);
            sensorSystem.setEnvironmentData(data);
            field.setLastEnvironmentData(data);
            logger.log("更新环境数据: " + data);
        } else {
            System.out.println("错误: 未找到农田 ID " + fieldId);
        }
    }

    public void showFieldEnvironment(String fieldId) {
        Field field = fields.get(fieldId);
        if (field != null && field.getLastEnvironmentData() != null) {
            System.out.println("\n=== " + field.getName() + " 的当前环境数据 ===");
            System.out.println(field.getLastEnvironmentData());
        } else {
            System.out.println("错误: 未找到农田 ID " + fieldId + " 或环境数据未初始化");
        }
    }

    // 任务管理
    public void createTask(String id, String name, String fieldId, String machineId, String description) {
        Field field = fields.get(fieldId);
        AgriculturalMachine machine = machines.get(machineId);

        if (field != null && machine != null) {
            Task task = new Task(id, name, field, machine, description);
            tasks.put(id, task);
            System.out.println("创建任务: " + name + " (ID: " + id + ")");
            System.out.println("- 农田: " + field.getName());
            System.out.println("- 农机: " + machine.getType());
            System.out.println("- 描述: " + description);
            logger.log("创建任务: " + name + " (ID: " + id + ")");
        } else {
            System.out.println("错误: 农田或农机不存在");
        }
    }

    public void showAllTasks() {
        System.out.println("\n=== 任务列表 ===");
        for (Map.Entry<String, Task> entry : tasks.entrySet()) {
            Task task = entry.getValue();
            System.out.println("ID: " + task.getId() + ", 名称: " + task.getName());
            System.out.println("- 状态: " + task.getStatus());
            System.out.println("- 农田: " + task.getField().getName());
            System.out.println("- 农机: " + task.getMachine().getType());
            System.out.println("- 描述: " + task.getDescription());
            System.out.println("- 创建时间: " + task.getCreateTime());
            if (task.getStartTime() != null) {
                System.out.println("- 开始时间: " + task.getStartTime());
            }
            if (task.getEndTime() != null) {
                System.out.println("- 结束时间: " + task.getEndTime());
            }
        }
    }

    public void executeTask(String taskId) {
        Task task = tasks.get(taskId);
        if (task != null) {
            if (task.getStatus() == Task.Status.CREATED) {
                Command command = new StartCommand(task.getMachine(), task);
                invoker.executeCommand(command);
                task.start();
            } else {
                System.out.println("错误: 任务状态不是'已创建'，无法执行");
            }
        } else {
            System.out.println("错误: 未找到任务 ID " + taskId);
        }
    }

    public void stopTask(String taskId) {
        Task task = tasks.get(taskId);
        if (task != null) {
            if (task.getStatus() == Task.Status.RUNNING) {
                Command command = new StopCommand(task.getMachine());
                invoker.executeCommand(command);
                task.stop();
            } else {
                System.out.println("错误: 任务状态不是'运行中'，无法停止");
            }
        } else {
            System.out.println("错误: 未找到任务 ID " + taskId);
        }
    }

    // 路径规划
    public void planPath(String machineId, String fieldId, int strategyType) {
        AgriculturalMachine machine = machines.get(machineId);
        Field field = fields.get(fieldId);

        if (machine != null && field != null) {
            PathPlanningStrategy strategy = switch (strategyType) {
                case 1 -> new NormalPathStrategy();
                case 2 -> new WetSoilPathStrategy();
                case 3 -> new ObstacleAvoidancePathStrategy();
                case 4 -> new CollaborativePathStrategy();
                default -> throw new IllegalArgumentException("无效策略类型: " + strategyType);
            };

            Command command = new ChangePathCommand(machine, field, strategy);
            invoker.executeCommand(command);
            logger.log("为 " + machine.getType() + " 在 " + field.getName() + " 规划路径，策略: " + strategy.getClass().getSimpleName());
        } else {
            System.out.println("错误: 农田或农机不存在");
        }
    }

    // 安全事件处理
    public void handleSafetyIssue(SafetyRequest request) {
        System.out.println("\n=== 处理安全事件 ===");
        safetyChain.handleRequest(request);
        logger.log("处理安全事件: " + request.getDescription());
    }

    // 用户管理
    public User login(String username, String password) {
        for (User user : users) {
            if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                System.out.println("用户 " + username + " 登录成功，角色: " + user.getRole());
                logger.log("用户 " + username + " 登录成功");
                return user;
            }
        }
        System.out.println("登录失败: 用户名或密码错误");
        logger.log("登录失败: 用户名或密码错误");
        return null;
    }

    public void addUser(String username, String realName, String password, User.Role role) {
        User user = new User(username, realName, password, role);
        users.add(user);
        System.out.println("添加用户: " + username + " (角色: " + role + ")");
        logger.log("添加用户: " + username + " (角色: " + role + ")");
    }

    public void showAllUsers() {
        System.out.println("\n=== 用户列表 ===");
        for (User user : users) {
            System.out.println("用户名: " + user.getUsername() +
                    ", 真实姓名: " + user.getRealName() +
                    ", 角色: " + user.getRole());
        }
    }

    // 系统管理
    public void showSystemStatus() {
        System.out.println("\n=== 系统状态 ===");
        System.out.println("在线农机: " + machines.size() + " 台");
        System.out.println("已注册农田: " + fields.size() + " 块");
        System.out.println("活跃任务: " + getActiveTaskCount() + " 个");
        System.out.println("系统运行时间: " + getSystemUptime() + " 小时");
        System.out.println("上次系统检查: " + getLastSystemCheckTime());
        logger.log("查看系统状态");
    }

    public void showCommandHistory() {
        invoker.showHistory();
    }

    public void showSystemLog() {
        logger.showLog();
    }

    // 辅助方法
    private int getActiveTaskCount() {
        return (int) tasks.values().stream()
                .filter(t -> t.getStatus() == Task.Status.RUNNING)
                .count();
    }

    private double getSystemUptime() {
        // 模拟系统运行时间
        return Math.round(Math.random() * 100) / 10.0;
    }

    private String getLastSystemCheckTime() {
        // 模拟上次系统检查时间
        LocalDateTime now = LocalDateTime.now();
        return now.minusHours((long) (Math.random() * 24)).toString();
    }
}

// 8. 代理模式：控制对农机设备的访问
class AgriculturalMachineProxy implements AgriculturalMachine {
    private AgriculturalMachine realMachine;
    private User user;

    public AgriculturalMachineProxy(AgriculturalMachine realMachine, User user) {
        this.realMachine = realMachine;
        this.user = user;
    }

    @Override
    public void start(Task task) {
        if (user.getRole() == User.Role.ADMIN || user.getRole() == User.Role.OPERATOR) {
            realMachine.start(task);
        } else {
            System.out.println("权限不足，无法启动 " + realMachine.getType());
        }
    }

    @Override
    public void stop() {
        if (user.getRole() == User.Role.ADMIN || user.getRole() == User.Role.OPERATOR) {
            realMachine.stop();
        } else {
            System.out.println("权限不足，无法停止 " + realMachine.getType());
        }
    }

    @Override
    public void changePath(Field field) {
        if (user.getRole() == User.Role.ADMIN || user.getRole() == User.Role.OPERATOR) {
            realMachine.changePath(field);
        } else {
            System.out.println("权限不足，无法更改 " + realMachine.getType() + " 的路径");
        }
    }

    @Override
    public void update(EnvironmentData data) {
        realMachine.update(data);
    }

    @Override
    public void setState(MachineState state) {
        realMachine.setState(state);
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        realMachine.setPathPlanningStrategy(strategy);
    }

    @Override
    public String getType() {
        return realMachine.getType();
    }

    @Override
    public String getStatus() {
        return realMachine.getStatus();
    }

    @Override
    public String getLocation() {
        return realMachine.getLocation();
    }

    @Override
    public double getFuelLevel() {
        return realMachine.getFuelLevel();
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        if (user.getRole() == User.Role.ADMIN || user.getRole() == User.Role.OPERATOR) {
            realMachine.adjustParameter(parameter, value);
        } else {
            System.out.println("权限不足，无法调整 " + realMachine.getType() + " 的参数");
        }
    }
}

// 9. 装饰器模式：动态给农机设备添加新功能
abstract class MachineDecorator implements AgriculturalMachine {
    protected AgriculturalMachine machine;

    public MachineDecorator(AgriculturalMachine machine) {
        this.machine = machine;
    }

    @Override
    public void start(Task task) {
        machine.start(task);
    }

    @Override
    public void stop() {
        machine.stop();
    }

    @Override
    public void changePath(Field field) {
        machine.changePath(field);
    }

    @Override
    public void update(EnvironmentData data) {
        machine.update(data);
    }

    @Override
    public void setState(MachineState state) {
        machine.setState(state);
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        machine.setPathPlanningStrategy(strategy);
    }

    @Override
    public String getType() {
        return machine.getType();
    }

    @Override
    public String getStatus() {
        return machine.getStatus();
    }

    @Override
    public String getLocation() {
        return machine.getLocation();
    }

    @Override
    public double getFuelLevel() {
        return machine.getFuelLevel();
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        machine.adjustParameter(parameter, value);
    }
}

class GPSEnhancedDecorator extends MachineDecorator {
    public GPSEnhancedDecorator(AgriculturalMachine machine) {
        super(machine);
    }

    @Override
    public void start(Task task) {
        super.start(task);
        System.out.println("启用高精度GPS定位系统，精度±2厘米");
    }

    @Override
    public String getLocation() {
        return super.getLocation() + " (高精度GPS)";
    }
}

class FertilizerSpreadCapabilityDecorator extends MachineDecorator {
    private double fertilizerLevel = 100.0;

    public FertilizerSpreadCapabilityDecorator(AgriculturalMachine machine) {
        super(machine);
    }

    @Override
    public void start(Task task) {
        super.start(task);
        System.out.println("启用自动施肥功能，肥料剩余: " + fertilizerLevel + "%");
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        if ("fertilizerRate".equalsIgnoreCase(parameter)) {
            System.out.println("调整施肥速率至: " + value + " 公斤/亩");
        } else {
            super.adjustParameter(parameter, value);
        }
    }

    public void refillFertilizer() {
        this.fertilizerLevel = 100.0;
        System.out.println("肥料已加满: " + fertilizerLevel + "%");
    }
}

class PesticideSprayCapabilityDecorator extends MachineDecorator {
    private double pesticideLevel = 100.0;

    public PesticideSprayCapabilityDecorator(AgriculturalMachine machine) {
        super(machine);
    }

    @Override
    public void start(Task task) {
        super.start(task);
        System.out.println("启用农药喷洒功能，农药剩余: " + pesticideLevel + "%");
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        if ("sprayRate".equalsIgnoreCase(parameter)) {
            System.out.println("调整喷洒速率至: " + value + " 升/亩");
        } else {
            super.adjustParameter(parameter, value);
        }
    }

    public void refillPesticide() {
        this.pesticideLevel = 100.0;
        System.out.println("农药已加满: " + pesticideLevel + "%");
    }
}

// 农机设备接口和实现
interface AgriculturalMachine extends Observer {
    void start(Task task);
    void stop();
    void changePath(Field field);
    void setState(MachineState state);
    void setPathPlanningStrategy(PathPlanningStrategy strategy);
    String getType();
    String getStatus();
    String getLocation();
    double getFuelLevel();
    void adjustParameter(String parameter, double value);
}

class Tractor implements AgriculturalMachine {
    private String type = "拖拉机";
    private MachineState state;
    private PathPlanningStrategy pathStrategy;
    private String location = "原点";
    private double fuelLevel = 85.0;
    private Task currentTask;

    public Tractor() {
        this.state = new IdleState();
        this.pathStrategy = new NormalPathStrategy();
    }

    @Override
    public void start(Task task) {
        this.currentTask = task;
        this.state = new WorkingState();
        state.execute(this);
        System.out.println("开始任务: " + task.getName() + " 在 " + task.getField().getName());
        simulateFuelConsumption();
    }

    @Override
    public void stop() {
        this.state = new MaintenanceState();
        state.execute(this);
        if (currentTask != null) {
            System.out.println("停止任务: " + currentTask.getName());
            currentTask = null;
        }
    }

    @Override
    public void changePath(Field field) {
        System.out.println(pathStrategy.planPath(field, this));
        updateLocation(field);
    }

    @Override
    public void update(EnvironmentData data) {
        System.out.println(type + " 收到 " + data.getField().getName() + " 的环境数据更新");

        if (currentTask != null && !currentTask.getField().getId().equals(data.getField().getId())) {
            System.out.println("当前任务在其他农田，忽略此环境数据");
            return;
        }

        if (data.isHasObstacle()) {
            this.state = new AlertState();
            state.execute(this);
            changePath(data.getField());
        } else if (data.getSoilMoisture() > 70) {
            this.state = new AlertState();
            state.execute(this);
            setPathPlanningStrategy(new WetSoilPathStrategy());
            changePath(data.getField());
        } else {
            this.state = new WorkingState();
            state.execute(this);
            changePath(data.getField());
        }
    }

    @Override
    public void setState(MachineState state) {
        this.state = state;
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        this.pathStrategy = strategy;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getStatus() {
        return type + " 当前状态: " + state.getStateName();
    }

    @Override
    public String getLocation() {
        return location;
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        System.out.println("调整 " + type + " 的 " + parameter + " 至 " + value);
        if ("speed".equalsIgnoreCase(parameter)) {
            System.out.println("设置行驶速度: " + value + " km/h");
        } else if ("traction".equalsIgnoreCase(parameter)) {
            System.out.println("设置牵引力: " + value + "%");
        } else {
            System.out.println("未知参数: " + parameter);
        }
    }

    private void updateLocation(Field field) {
        // 模拟位置更新
        this.location = field.getName() + "区域内";
        System.out.println(type + " 位置更新为: " + location);
    }

    private void simulateFuelConsumption() {
        // 模拟燃油消耗
        this.fuelLevel -= Math.random() * 5;
        if (fuelLevel < 20) {
            SafetyRequest request = new SafetyRequest(
                    SafetyRequest.Type.LOW_FUEL,
                    type + " 燃油不足",
                    fuelLevel,
                    2.5 // 模拟到加油站距离
            );
            SafetyHandler safetyChain = new LowFuelHandler();
            safetyChain.handleRequest(request);
        }
    }
}

class Seeder implements AgriculturalMachine {
    private String type = "播种机";
    private MachineState state;
    private PathPlanningStrategy pathStrategy;
    private String location = "原点";
    private double fuelLevel = 90.0;
    private Task currentTask;
    private double seedLevel = 100.0;

    public Seeder() {
        this.state = new IdleState();
        this.pathStrategy = new NormalPathStrategy();
    }

    @Override
    public void start(Task task) {
        this.currentTask = task;
        this.state = new WorkingState();
        state.execute(this);
        System.out.println("开始任务: " + task.getName() + " 在 " + task.getField().getName());
        System.out.println("种子剩余: " + seedLevel + "%");
        simulateFuelConsumption();
    }

    @Override
    public void stop() {
        this.state = new MaintenanceState();
        state.execute(this);
        if (currentTask != null) {
            System.out.println("停止任务: " + currentTask.getName());
            currentTask = null;
        }
    }

    @Override
    public void changePath(Field field) {
        System.out.println(pathStrategy.planPath(field, this));
        updateLocation(field);
    }

    @Override
    public void update(EnvironmentData data) {
        System.out.println(type + " 收到 " + data.getField().getName() + " 的环境数据更新");

        if (currentTask != null && !currentTask.getField().getId().equals(data.getField().getId())) {
            System.out.println("当前任务在其他农田，忽略此环境数据");
            return;
        }

        if (data.isHasObstacle()) {
            this.state = new AlertState();
            state.execute(this);
            changePath(data.getField());
        } else if (data.getSoilMoisture() > 70) {
            System.out.println(type + " 调整播种策略：推迟播种，土壤湿度过高");
        } else {
            this.state = new WorkingState();
            state.execute(this);
            changePath(data.getField());
        }
    }

    @Override
    public void setState(MachineState state) {
        this.state = state;
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        this.pathStrategy = strategy;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getStatus() {
        return type + " 当前状态: " + state.getStateName() + ", 种子剩余: " + seedLevel + "%";
    }

    @Override
    public String getLocation() {
        return location;
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        System.out.println("调整 " + type + " 的 " + parameter + " 至 " + value);
        if ("seedingDepth".equalsIgnoreCase(parameter)) {
            System.out.println("设置播种深度: " + value + " 厘米");
        } else if ("seedingRate".equalsIgnoreCase(parameter)) {
            System.out.println("设置播种密度: " + value + " 粒/平方米");
        } else {
            System.out.println("未知参数: " + parameter);
        }
    }

    private void updateLocation(Field field) {
        // 模拟位置更新
        this.location = field.getName() + "区域内";
        System.out.println(type + " 位置更新为: " + location);
    }

    private void simulateFuelConsumption() {
        // 模拟燃油和种子消耗
        this.fuelLevel -= Math.random() * 3;
        this.seedLevel -= Math.random() * 10;

        if (fuelLevel < 20) {
            SafetyRequest request = new SafetyRequest(
                    SafetyRequest.Type.LOW_FUEL,
                    type + " 燃油不足",
                    fuelLevel,
                    2.5 // 模拟到加油站距离
            );
            SafetyHandler safetyChain = new LowFuelHandler();
            safetyChain.handleRequest(request);
        }

        if (seedLevel < 10) {
            System.out.println("警告: 种子即将耗尽，剩余 " + seedLevel + "%");
        }
    }
}

class Harvester implements AgriculturalMachine {
    private String type = "收割机";
    private MachineState state;
    private PathPlanningStrategy pathStrategy;
    private String location = "原点";
    private double fuelLevel = 80.0;
    private Task currentTask;
    private double grainCapacity = 0.0;
    private double maxGrainCapacity = 100.0;

    public Harvester() {
        this.state = new IdleState();
        this.pathStrategy = new NormalPathStrategy();
    }

    @Override
    public void start(Task task) {
        this.currentTask = task;
        this.state = new WorkingState();
        state.execute(this);
        System.out.println("开始任务: " + task.getName() + " 在 " + task.getField().getName());
        System.out.println("谷物容量: " + grainCapacity + "/" + maxGrainCapacity);
        simulateFuelConsumption();
    }

    @Override
    public void stop() {
        this.state = new MaintenanceState();
        state.execute(this);
        if (currentTask != null) {
            System.out.println("停止任务: " + currentTask.getName());
            currentTask = null;
        }
    }

    @Override
    public void changePath(Field field) {
        System.out.println(pathStrategy.planPath(field, this));
        updateLocation(field);
    }

    @Override
    public void update(EnvironmentData data) {
        System.out.println(type + " 收到 " + data.getField().getName() + " 的环境数据更新");

        if (currentTask != null && !currentTask.getField().getId().equals(data.getField().getId())) {
            System.out.println("当前任务在其他农田，忽略此环境数据");
            return;
        }

        if (data.isHasObstacle()) {
            this.state = new AlertState();
            state.execute(this);
            changePath(data.getField());
        } else if (grainCapacity >= maxGrainCapacity * 0.9) {
            System.out.println(type + " 谷物容量接近上限，准备返回卸载点");
            setPathPlanningStrategy(new NormalPathStrategy());
            changePath(data.getField());
        } else {
            this.state = new WorkingState();
            state.execute(this);
            changePath(data.getField());
        }
    }

    @Override
    public void setState(MachineState state) {
        this.state = state;
    }

    @Override
    public void setPathPlanningStrategy(PathPlanningStrategy strategy) {
        this.pathStrategy = strategy;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getStatus() {
        return type + " 当前状态: " + state.getStateName() +
                ", 燃油: " + fuelLevel + "%," +
                " 谷物容量: " + grainCapacity + "/" + maxGrainCapacity;
    }

    @Override
    public String getLocation() {
        return location;
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public void adjustParameter(String parameter, double value) {
        System.out.println("调整 " + type + " 的 " + parameter + " 至 " + value);
        if ("cuttingWidth".equalsIgnoreCase(parameter)) {
            System.out.println("设置收割宽度: " + value + " 米");
        } else if ("threshingIntensity".equalsIgnoreCase(parameter)) {
            System.out.println("设置脱粒强度: " + value + "%");
        } else {
            System.out.println("未知参数: " + parameter);
        }
    }

    private void updateLocation(Field field) {
        this.location = field.getName() + "区域内";
        System.out.println(type + " 位置更新为: " + location);
    }

    private void simulateFuelConsumption() {
        this.fuelLevel -= Math.random() * 4;
        this.grainCapacity += Math.random() * 15;

        if (grainCapacity >= maxGrainCapacity) {
            grainCapacity = maxGrainCapacity;
            System.out.println("警告: 谷物容量已满，需要卸载");
        }

        if (fuelLevel < 20) {
            SafetyRequest request = new SafetyRequest(
                    SafetyRequest.Type.LOW_FUEL,
                    type + " 燃油不足",
                    fuelLevel,
                    2.5
            );
            SafetyHandler safetyChain = new LowFuelHandler();
            safetyChain.handleRequest(request);
        }
    }
}
public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static AgriculturalSystemFacade system;
    private static User currentUser;

    public static void main(String[] args) {
        system = new AgriculturalSystemFacade();
        login();
        showMainMenu();
    }

    // 用户登录
    private static void login() {
        while (currentUser == null) {
            System.out.println("\n=== 智能农机系统登录 ===");
            System.out.print("用户名: ");
            String username = scanner.nextLine();
            System.out.print("密码: ");
            String password = scanner.nextLine();

            currentUser = system.login(username, password);
            if (currentUser == null) {
                System.out.println("登录失败，请重试");
            }
        }
    }

    // 主菜单
    private static void showMainMenu() {
        boolean running = true;
        while (running) {
            System.out.println("\n=== 欢迎 " + currentUser.getRealName() + " (" + currentUser.getRole() + ") ===");
            System.out.println("1. 农机设备管理");
            System.out.println("2. 农田环境监测");
            System.out.println("3. 智能路径规划");
            System.out.println("4. 任务执行与控制");
            System.out.println("5. 系统管理");
            System.out.println("6. 退出系统");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    manageMachines();
                    break;
                case 2:
                    monitorEnvironment();
                    break;
                case 3:
                    planPaths();
                    break;
                case 4:
                    manageTasks();
                    break;
                case 5:
                    systemManagement();
                    break;
                case 6:
                    running = false;
                    System.out.println("感谢使用智能农机系统，再见！");
                    break;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 农机设备管理菜单
    private static void manageMachines() {
        while (true) {
            System.out.println("\n=== 农机设备管理 ===");
            System.out.println("1. 查看所有农机");
            System.out.println("2. 添加农机");
            System.out.println("3. 移除农机");
            System.out.println("4. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    system.showAllMachines();
                    break;
                case 2:
                    addMachine();
                    break;
                case 3:
                    removeMachine();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 添加农机
    private static void addMachine() {
        if (currentUser.getRole() != User.Role.ADMIN) {
            System.out.println("权限不足，需要管理员角色");
            return;
        }

        System.out.print("输入农机ID: ");
        String id = scanner.nextLine();

        System.out.println("选择农机类型:");
        System.out.println("1. 拖拉机");
        System.out.println("2. 播种机");
        System.out.println("3. 收割机");
        System.out.println("4. 喷药机");
        int type = getIntInput();

        AgriculturalMachineFactory factory = switch (type) {
            case 1 -> new TractorFactory();
            case 2 -> new SeederFactory();
            case 3 -> new HarvesterFactory();
            case 4 -> new SprayerFactory();
            default -> null;
        };

        if (factory != null) {
            system.addMachine(id, factory.createMachine());
        } else {
            System.out.println("无效的农机类型");
        }
    }

    // 移除农机
    private static void removeMachine() {
        if (currentUser.getRole() != User.Role.ADMIN) {
            System.out.println("权限不足，需要管理员角色");
            return;
        }

        System.out.print("输入要移除的农机ID: ");
        String id = scanner.nextLine();
        system.removeMachine(id);
    }

    // 农田环境监测菜单
    private static void monitorEnvironment() {
        while (true) {
            System.out.println("\n=== 农田环境监测 ===");
            System.out.println("1. 查看所有农田");
            System.out.println("2. 更新环境数据");
            System.out.println("3. 查看农田环境");
            System.out.println("4. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    system.showAllFields();
                    break;
                case 2:
                    updateEnvironmentData();
                    break;
                case 3:
                    viewFieldEnvironment();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 更新环境数据
    private static void updateEnvironmentData() {
        if (currentUser.getRole() != User.Role.ADMIN && currentUser.getRole() != User.Role.OPERATOR) {
            System.out.println("权限不足，需要管理员或操作员角色");
            return;
        }

        system.showAllFields();
        System.out.print("选择农田ID: ");
        String fieldId = scanner.nextLine();

        System.out.print("土壤湿度(0-100): ");
        double moisture = getDoubleInput();

        System.out.print("土壤pH值(0-14): ");
        double ph = getDoubleInput();

        System.out.print("养分含量(0-100): ");
        double nutrient = getDoubleInput();

        System.out.print("温度(°C): ");
        double temp = getDoubleInput();

        System.out.print("湿度(%): ");
        double humidity = getDoubleInput();

        System.out.print("风速(m/s): ");
        double wind = getDoubleInput();

        System.out.print("是否有障碍物(1=有, 0=无): ");
        boolean obstacle = getIntInput() == 1;

        system.updateEnvironment(fieldId, moisture, ph, nutrient, temp, humidity, wind, obstacle);
    }

    // 查看农田环境
    private static void viewFieldEnvironment() {
        system.showAllFields();
        System.out.print("选择农田ID: ");
        String fieldId = scanner.nextLine();
        system.showFieldEnvironment(fieldId);
    }

    // 智能路径规划菜单
    private static void planPaths() {
        while (true) {
            System.out.println("\n=== 智能路径规划 ===");
            System.out.println("1. 查看所有农机");
            System.out.println("2. 查看所有农田");
            System.out.println("3. 为农机规划路径");
            System.out.println("4. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    system.showAllMachines();
                    break;
                case 2:
                    system.showAllFields();
                    break;
                case 3:
                    planMachinePath();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 为农机规划路径
    private static void planMachinePath() {
        if (currentUser.getRole() != User.Role.ADMIN && currentUser.getRole() != User.Role.OPERATOR) {
            System.out.println("权限不足，需要管理员或操作员角色");
            return;
        }

        system.showAllMachines();
        System.out.print("选择农机ID: ");
        String machineId = scanner.nextLine();

        system.showAllFields();
        System.out.print("选择农田ID: ");
        String fieldId = scanner.nextLine();

        System.out.println("选择路径策略:");
        System.out.println("1. 正常路径");
        System.out.println("2. 湿土路径");
        System.out.println("3. 避障路径");
        System.out.println("4. 协同路径");
        int strategy = getIntInput();

        system.planPath(machineId, fieldId, strategy);
    }

    // 任务执行与控制菜单
    private static void manageTasks() {
        while (true) {
            System.out.println("\n=== 任务执行与控制 ===");
            System.out.println("1. 查看所有任务");
            System.out.println("2. 创建新任务");
            System.out.println("3. 执行任务");
            System.out.println("4. 停止任务");
            System.out.println("5. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    system.showAllTasks();
                    break;
                case 2:
                    createTask();
                    break;
                case 3:
                    executeTask();
                    break;
                case 4:
                    stopTask();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 创建任务
    private static void createTask() {
        if (currentUser.getRole() != User.Role.ADMIN && currentUser.getRole() != User.Role.OPERATOR) {
            System.out.println("权限不足，需要管理员或操作员角色");
            return;
        }

        System.out.print("输入任务ID: ");
        String taskId = scanner.nextLine();

        System.out.print("输入任务名称: ");
        String taskName = scanner.nextLine();

        system.showAllFields();
        System.out.print("选择农田ID: ");
        String fieldId = scanner.nextLine();

        system.showAllMachines();
        System.out.print("选择农机ID: ");
        String machineId = scanner.nextLine();

        System.out.print("输入任务描述: ");
        String description = scanner.nextLine();

        system.createTask(taskId, taskName, fieldId, machineId, description);
    }

    // 执行任务
    private static void executeTask() {
        if (currentUser.getRole() != User.Role.ADMIN && currentUser.getRole() != User.Role.OPERATOR) {
            System.out.println("权限不足，需要管理员或操作员角色");
            return;
        }

        system.showAllTasks();
        System.out.print("选择要执行的任务ID: ");
        String taskId = scanner.nextLine();
        system.executeTask(taskId);
    }

    // 停止任务
    private static void stopTask() {
        if (currentUser.getRole() != User.Role.ADMIN && currentUser.getRole() != User.Role.OPERATOR) {
            System.out.println("权限不足，需要管理员或操作员角色");
            return;
        }

        system.showAllTasks();
        System.out.print("选择要停止的任务ID: ");
        String taskId = scanner.nextLine();
        system.stopTask(taskId);
    }

    // 系统管理菜单
    private static void systemManagement() {
        if (currentUser.getRole() != User.Role.ADMIN) {
            System.out.println("权限不足，需要管理员角色");
            return;
        }

        while (true) {
            System.out.println("\n=== 系统管理 ===");
            System.out.println("1. 查看系统状态");
            System.out.println("2. 查看命令历史");
            System.out.println("3. 查看系统日志");
            System.out.println("4. 查看用户列表");
            System.out.println("5. 添加用户");
            System.out.println("6. 处理安全事件");
            System.out.println("7. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = getIntInput();
            switch (choice) {
                case 1:
                    system.showSystemStatus();
                    break;
                case 2:
                    system.showCommandHistory();
                    break;
                case 3:
                    system.showSystemLog();
                    break;
                case 4:
                    system.showAllUsers();
                    break;
                case 5:
                    addUser();
                    break;
                case 6:
                    handleSafetyIssue();
                    break;
                case 7:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    // 添加用户
    private static void addUser() {
        System.out.print("输入用户名: ");
        String username = scanner.nextLine();

        System.out.print("输入真实姓名: ");
        String realName = scanner.nextLine();

        System.out.print("输入密码: ");
        String password = scanner.nextLine();

        System.out.println("选择用户角色:");
        System.out.println("1. 管理员");
        System.out.println("2. 操作员");
        System.out.println("3. 查看者");
        int roleChoice = getIntInput();

        User.Role role = switch (roleChoice) {
            case 1 -> User.Role.ADMIN;
            case 2 -> User.Role.OPERATOR;
            case 3 -> User.Role.VIEWER;
            default -> User.Role.VIEWER;
        };

        system.addUser(username, realName, password, role);
    }

    // 处理安全事件
    private static void handleSafetyIssue() {
        System.out.println("选择安全事件类型:");
        System.out.println("1. 障碍物");
        System.out.println("2. 湿土");
        System.out.println("3. 设备故障");
        System.out.println("4. 低油量");
        int typeChoice = getIntInput();

        System.out.print("输入事件描述: ");
        String description = scanner.nextLine();

        SafetyRequest.Type type = switch (typeChoice) {
            case 1 -> SafetyRequest.Type.OBSTACLE;
            case 2 -> SafetyRequest.Type.WET_SOIL;
            case 3 -> SafetyRequest.Type.FAULT;
            case 4 -> SafetyRequest.Type.LOW_FUEL;
            default -> null;
        };

        if (type != null) {
            SafetyRequest request;
            if (type == SafetyRequest.Type.FAULT) {
                System.out.print("输入故障代码: ");
                int code = getIntInput();
                request = new SafetyRequest(type, description, code);
            } else if (type == SafetyRequest.Type.LOW_FUEL) {
                System.out.print("输入当前油量(%): ");
                double fuel = getDoubleInput();
                System.out.print("输入到加油站距离(km): ");
                double distance = getDoubleInput();
                request = new SafetyRequest(type, description, fuel, distance);
            } else {
                request = new SafetyRequest(type, description);
            }

            system.handleSafetyIssue(request);
        } else {
            System.out.println("无效的事件类型");
        }
    }

    // 获取整数输入
    private static int getIntInput() {
        try {
            return Integer.parseInt(scanner.nextLine());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    // 获取双精度输入
    private static double getDoubleInput() {
        try {
            return Double.parseDouble(scanner.nextLine());
        } catch (NumberFormatException e) {
            return -1;
        }
    }
}